import java.util.PriorityQueue;

class MyTimerTask1 implements Comparable<MyTimerTask1>{
    private Runnable runnable;
    private long time;

    public MyTimerTask1(Runnable runnable, long time) {
        this.runnable = runnable;
        this.time = System.currentTimeMillis() + time;
    }

    @Override
    public int compareTo(MyTimerTask1 o) {
        return (int) (this.time - o.time);
    }

    public long getTime() {
        return time;
    }

    public Runnable getRunnable() {
        return runnable;
    }
}

public class MyTimer1 {
    private PriorityQueue<MyTimerTask1> priorityQueue = new PriorityQueue<>();
    private Object locker = new Object();

    public void schedule(Runnable runnable, long time){
        synchronized (locker){
            priorityQueue.offer(new MyTimerTask1(runnable, time));
            locker.notify();
        }
    }

    public MyTimer1() {
        Thread thread = new Thread(() -> {
            while(true){
                synchronized (locker){
                    while(priorityQueue.isEmpty()){
                        try {
                            locker.wait();
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                    long curtime = System.currentTimeMillis();
                    MyTimerTask1 timerTask = priorityQueue.peek();
                    if(curtime >= timerTask.getTime()){
                        timerTask.getRunnable().run();
                        priorityQueue.poll();
                    }else{
                        try {
                            locker.wait(timerTask.getTime() - curtime);
                        } catch (InterruptedException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            }
        });
        thread.start();
    }

    public static void main(String[] args) throws InterruptedException {
        MyTimer1 myTimer = new MyTimer1();
        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("3000");
            }
        }, 3000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("2000");
            }
        }, 2000);

        myTimer.schedule(new Runnable() {
            @Override
            public void run() {
                System.out.println("1000");
            }
        }, 1000);
    }
}

